package reduce.fz.com.reduce.util.oss.model;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.pm.ApplicationInfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.JsonUtil;

public class FederationTokenGetter {

    private static FederationToken token;

    public static FederationToken getToken(String serverAddress, String userId) {
        token = getTokenFromServer(serverAddress, userId);
        return token;
    }

    private static FederationToken getTokenFromServer(String serverAddress, String userId) {
        String queryUrl =  HttpUtils.request_domain + "api/v1/sts/token?user-name=" + userId;
        String responseStr = null;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(queryUrl);
            HttpResponse hr = client.execute(httpGet);
            responseStr = EntityUtils.toString(hr.getEntity());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (responseStr == null) {
            return null;
        }
        try {
            Result<FederationToken> data = JsonUtil.convert(responseStr, new TypeReference<Result<FederationToken>>() {
            });
            FederationToken token = data.getData();
            return token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
